package com.xm9m.web.service.api;

import com.salesmanager.core.business.product.Product;
import com.salesmanager.core.business.product.service.ProductService;
import com.salesmanager.core.business.statistics.model.ProductCriteria;
import com.salesmanager.web.model.paging.PaginationDataList;
import com.xm9m.web.service.api.request.ProductRequest;
import com.xm9m.web.service.api.response.ProductResponse;
import com.xm9m.web.service.constants.AppConstants;
import com.xm9m.web.service.constants.StatusCode;
import com.xm9m.web.service.entity.ProductItem;
import com.xm9m.web.service.interfaces.AbstractRestApi;
import com.xm9m.web.service.interfaces.IXm9mResponse;
import com.xm9m.web.service.internal.util.BuildResponseUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by LiuTong on 2017/11/24.
 */
public class ProductListGet extends AbstractRestApi {
    private static final Logger logger = LoggerFactory.getLogger(ProductListGet.class);

    @Autowired
    private ProductService productService;

    @Override
    public <T extends IXm9mResponse> T execute(String requestData, String version) throws Exception {
        ProductResponse response=new ProductResponse();
        ProductRequest request = super.json2Bean(requestData, ProductRequest.class);
        if (request == null) {
            return  (T) BuildResponseUtil.buildSimpleResponse(StatusCode.PARAM_WRONG);
        }

        ProductCriteria criteria = new ProductCriteria();

        if(request.getCurrentPage()>0){
            criteria.setStartIndex(request.getPageSize() * (request.getCurrentPage() - 1));
        }
        if (request.getPageSize()>0) {
            criteria.setMaxCount(request.getPageSize());
        }else{
            criteria.setMaxCount(AppConstants.PAGE_SIZE);
        }

        if (!StringUtils.isBlank(request.getName())){
            criteria.setProductName(request.getName());
        }

        PaginationDataList<Product> dataList = productService.getProductList(criteria);

        response.setTotalCount(dataList.getTotalCount());
        List<ProductItem> list = new ArrayList<ProductItem>();
        for(Product product : dataList.getData()){
            ProductItem item = new ProductItem();
            item.setCode(product.getProductCode());
            item.setName(product.getProductName());
            list.add(item);
        }
        response.setData(list);
        return (T) response;
    }
}
